package cloud.mbase.aspect;

import org.aspectj.lang.annotation.Aspect;
import org.springframework.aop.Advisor;
import org.springframework.aop.aspectj.AspectJExpressionPointcut;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.interceptor.*;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class TransactionAspect {
    private static final int TX_METHOD_TIMEOUT = 5000;
    private static final String AOP_POINTCUT_EXPRESSION = "execution (public * cloud.mbase.business.*.*(..))";
    private final PlatformTransactionManager transactionManager;

    @Autowired
    public TransactionAspect(PlatformTransactionManager transactionManager) {
        this.transactionManager = transactionManager;
    }

    @Bean
    public TransactionInterceptor txAdvice() {
        NameMatchTransactionAttributeSource source = new NameMatchTransactionAttributeSource();
        /*只读事务，不做更新操作*/
        RuleBasedTransactionAttribute readonlyTx = new RuleBasedTransactionAttribute();
        readonlyTx.setReadOnly(true);
        readonlyTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_NOT_SUPPORTED);
        /*当前存在事务就使用当前事务，当前不存在事务就创建一个新的事务*/
        RuleBasedTransactionAttribute requiedTx = new RuleBasedTransactionAttribute();
        requiedTx.setRollbackRules(
                Collections.singletonList(new RollbackRuleAttribute(Exception.class))
        );
        requiedTx.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        requiedTx.setTimeout(TX_METHOD_TIMEOUT);
        Map<String, TransactionAttribute> txAttribute = new HashMap<>();
        txAttribute.put("add*", requiedTx);
        txAttribute.put("save*", requiedTx);
        txAttribute.put("set*", requiedTx);
        txAttribute.put("insert*", requiedTx);
        txAttribute.put("update*", requiedTx);
        txAttribute.put("delete*", requiedTx);
        txAttribute.put("get*", readonlyTx);
        txAttribute.put("query*", readonlyTx);
        txAttribute.put("find*", readonlyTx);
        source.setNameMap(txAttribute);
        TransactionInterceptor txAdviceIns = new TransactionInterceptor(transactionManager, source);
        return txAdviceIns;
    }

    @Bean
    public Advisor txAdviceAdvisor() {
        AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
        pointcut.setExpression(AOP_POINTCUT_EXPRESSION);
        return new DefaultPointcutAdvisor(pointcut, txAdvice());
    }
}
